{% extends 'admin/change_list.html' %}
{% load static %}

{% block object-tools-items %}
{{ block.super }}
<!-- 在此处引入外部样式表 -->
<link rel="stylesheet" href="{% static 'css/chat_styles.css' %}">
{% endblock %}

{% block extrahead %}
{{ block.super }}

<!-- 引入所需的JavaScript库 -->
<script src="{% static 'js/marked.min.js' %}"></script>
<script src="{% static 'js/purify.min.js' %}"></script>
<script src="{% static 'js/Chart.min.js' %}"></script>

<div id="resultModal" class="modal">
    <div class="chat-window">
        <div class="chat-header">AI Analysis Chat</div>
        <div id="chatContent" class="chat-content">
            <!-- 聊天块将插入此处 -->
        </div>
        <div class="chat-footer">
            <div class="button-container" id="functionButtons">
                <!-- 功能按钮将插入此处 -->
            </div>
            <div class="workflow-button-container" id="workflowButtons">
                <!-- 工作流按钮将插入此处 -->
            </div>
        </div>
    </div>
</div>

<div id="floatingPanel">
    <a class="button"
       href="javascript:void(0);"
       onclick="openChatWindow()">Open AI Chat</a>
</div>

<script type="text/javascript">
    document.addEventListener('DOMContentLoaded', function() {
        // 加载并初始化功能按钮
        loadAndInitializeButtons('/experiments/get-prompts/', 'functionButtons', analyzeWithTemplate);

        // 加载并初始化工作流按钮
        loadAndInitializeButtons('/experiments/get-workflow/', 'workflowButtons', demoWorkflowFunction);

        initializeButtons();

        // 监听可编辑块的焦点事件，以便将其移动到底部
        const chatContent = document.getElementById('chatContent');
        if (chatContent) {
            chatContent.addEventListener('focusin', function(event) {
                if (event.target.classList.contains('chat-block') && event.target.isContentEditable) {
                    moveToBottom(event.target);
                }
            });
        }
    });

    // 打开模态框
    function openModal() {
        const modal = document.getElementById('resultModal');
        if (modal) {
            modal.style.display = 'block';
            window.onclick = function(event) {
                if (event.target == modal) {
                    modal.style.display = 'none';
                }
            };
        }
    }

    // 点击“Open AI Chat”按钮时调用
    function openChatWindow() {
        const selectedCheckboxes = document.querySelectorAll('input[name=_selected_action]:checked');
        const selected = Array.from(selectedCheckboxes).map(cb => cb.value);

        openModal();

        if (selected.length === 0) {
            createChatBlock("", true);
        } else {
            const appLabel = '{{ opts.app_label }}';
            const modelName = '{{ opts.model_name }}';

            fetch('/experiments/fetch_selected_items/', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]').value,
                },
                body: JSON.stringify({ app_label: appLabel, model_name: modelName, item_ids: selected }),
            })
            .then(response => response.json())
            .then(data => {
                if (data.items_data) {
                    createChatBlock(data.items_data, true);
                } else {
                    alert(`Error: ${data.error}`);
                }
            })
            .catch(error => {
                console.error('Error fetching data:', error);
                alert('发生错误，请稍后重试。');
            });
        }
    }

    // 初始化基础按钮
    function initializeButtons() {
        const chatContent = document.getElementById('chatContent');

        if (chatContent) {
            const plusButton = document.createElement('button');
            plusButton.id = 'addChatBlockButton';
            plusButton.textContent = '+';
            plusButton.onclick = createEditableChatBlock;

            const spinner = document.createElement('div');
            spinner.className = 'loading-spinner';
            spinner.id = 'loadingSpinner';

            chatContent.appendChild(spinner);
            chatContent.appendChild(plusButton);
        }
    }

    // 显示或隐藏加号按钮
    function togglePlusButton(show) {
        const plusButton = document.getElementById('addChatBlockButton');
        const spinner = document.getElementById('loadingSpinner');

        if (plusButton && spinner) {
            if (show) {
                plusButton.style.display = 'block';
                spinner.style.display = 'none';
            } else {
                plusButton.style.display = 'none';
                spinner.style.display = 'block';
            }
        }
    }

    // 加载和初始化按钮，通用函数
    function loadAndInitializeButtons(url, buttonContainerId, clickHandler) {
    console.log(`Fetching data from: ${url}`);

    fetch(url)
    .then(response => {
        if (!response.ok) {
            throw new Error(`Network response was not ok: ${response.statusText}`);
        }
        return response.json();
    })
    .then(items => {
        const buttonContainer = document.getElementById(buttonContainerId);

        if (!buttonContainer) {
            console.error(`Button container with id '${buttonContainerId}' not found.`);
            return;
        }

        if (items.length === 0) {
            console.log(`No items found for URL: ${url}`);
        } else {
            console.log(`Received ${items.length} items.`);
        }

        items.forEach(item => {
            const button = document.createElement('button');
            button.textContent = item.name;
            button.onclick = function() {
                console.log(`Button clicked: ${item.name}`);
                clickHandler(item.template || item.description);
            };
            buttonContainer.appendChild(button);
        });
    })
    .catch(error => {
        console.error(`Error loading data from ${url}:`, error);
        // 可选择在页面上显示用户友好的错误信息
        alert("An error occurred while loading buttons. Please try again later.");
    });
    }

   // 通用请求发送函数
    function sendAnalysisRequest(url, template, successCallback) {
        const selectedBlock = document.querySelector('.chat-block.selected');

        if (!selectedBlock) {
            alert("先选中一个对话窗口再发送给AI");
            return;
        }

        const table = selectedBlock.querySelector('table');
        let formattedTableMarkdown = '';

        if (table) {
            const headers = Array.from(table.querySelectorAll('thead th'))
                .filter(th => th.style.display !== 'none')
                .map(th => th.textContent.trim());

            const rows = Array.from(table.querySelectorAll('tbody tr')).map(tr => {
                return Array.from(tr.querySelectorAll('td'))
                    .filter(td => td.style.display !== 'none')
                    .map(td => td.textContent.trim());
            });

            if (headers.length > 0 && rows.length > 0) {
                const separatorRow = headers.map(() => '---').join(' | ');
                const headerRow = headers.join(' | ');
                const dataRows = rows.map(cells => cells.join(' | ')).join('\n');
                formattedTableMarkdown = `| ${headerRow} |\n| ${separatorRow} |\n${dataRows}`;
            }
        }

        const userText = selectedBlock.innerHTML.split('</table>')[1]?.trim() || selectedBlock.innerText.trim();

        const messages = [
            { "role": "system", "content": template },
            { "role": "user", "content": `${formattedTableMarkdown}\n${userText}` }
        ];

        showLoadingSpinner();
        moveToBottom(selectedBlock);

        fetch(url, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]').value,
            },
            body: JSON.stringify({ messages: messages }),
        })
        .then(response => response.json())
        .then(result => {
            hideLoadingSpinner();
            if (result.error) {
                createChatBlock(`AI Error: ${result.error}`, false);
            } else {
                if (result.response) {
                    successCallback(result.response);
                }
            }
        })
        .catch(error => {
            hideLoadingSpinner();
            console.error('Error analyzing data:', error);
        });
    }

    // 示例工作流函数
    function demoWorkflowFunction(description) {
        console.log('Description:', description);
        sendAnalysisRequest('/experiments/ai-analysis/', description, function(response) {
            createChatBlock(response, false);
        });
    }

    // 使用模板进行分析
    function analyzeWithTemplate(template) {
        console.log('template:', template);
        sendAnalysisRequest('/experiments/ai-analysis/', template, function(response) {
            createChatBlock(response, false);
        });
    }

    // 创建新的聊天块
    function createChatBlock(content, isInput = false) {
        const chatContent = document.getElementById('chatContent');

        if (chatContent) {
            const chatBlock = document.createElement('div');
            chatBlock.className = 'chat-block';
            chatBlock.classList.add(isInput ? 'input-block' : 'response-block');
            chatBlock.setAttribute('contenteditable', isInput);

            if (isInput) {
                const renderedHTML = marked.parse(content);
                const safeHTML = DOMPurify.sanitize(renderedHTML);
                chatBlock.innerHTML = safeHTML;

                const table = chatBlock.querySelector('table');
                if (table) {
                    createColumnControlPanel(table, chatBlock);
                }
            } else {
                chatBlock.innerHTML = content;
            }

            chatBlock.onclick = function(event) {
                document.querySelectorAll('.chat-block').forEach(block => block.classList.remove('selected'));
                chatBlock.classList.add('selected');
            };

            chatContent.insertBefore(chatBlock, document.getElementById('addChatBlockButton'));
            movePlusButtonToBottom();
            setTimeout(() => {
                chatContent.scrollTop = chatContent.scrollHeight;
                const scripts = chatBlock.getElementsByTagName('script');
                for (let i = 0; i < scripts.length; i++) {
                    try {
                        const scriptElement = document.createElement('script');
                        scriptElement.text = scripts[i].innerHTML;
                        document.body.appendChild(scriptElement);
                        document.body.removeChild(scriptElement);
                    } catch (e) {
                        console.error("Error executing script:", e);
                    }
                }
            }, 0);
        }
    }

    // 将加号按钮移到最底部
    function movePlusButtonToBottom() {
        const chatContent = document.getElementById('chatContent');
        const plusButton = document.getElementById('addChatBlockButton');
        const spinner = document.getElementById('loadingSpinner');

        if (chatContent && plusButton && spinner) {
            chatContent.appendChild(plusButton);
            chatContent.appendChild(spinner);
        }
    }

    // 确保每次显示/隐藏加号按钮时更新底部位置
    function togglePlusButton(show) {
        const plusButton = document.getElementById('addChatBlockButton');
        const spinner = document.getElementById('loadingSpinner');

        if (plusButton && spinner) {
            if (show) {
                plusButton.style.display = 'block';
                spinner.style.display = 'none';
            } else {
                plusButton.style.display = 'none';
                spinner.style.display = 'block';
            }

            movePlusButtonToBottom();
        }
    }

    // 将选中的 chat-block 移动到最底部的方法
    function moveToBottom(element) {
        const chatContent = document.getElementById('chatContent');
        const plusButton = document.getElementById('addChatBlockButton');

        if (chatContent && plusButton && element.nextSibling !== plusButton) {
            chatContent.insertBefore(element, plusButton);

            setTimeout(() => {
                chatContent.scrollTop = chatContent.scrollHeight;
                element.focus();
            }, 0);
        }
    }

   // 创建列控制面板
    function createColumnControlPanel(table, chatBlock) {
        const headerRow = table.querySelector('thead tr');
        if (!headerRow) return;

        // 获取列标题
        const columnHeaders = Array.from(headerRow.children).map(th => th.textContent.trim());
        const controlPanel = document.createElement('div');
        controlPanel.style.marginBottom = '10px';

        columnHeaders.forEach((header, index) => {
            const label = document.createElement('label');
            label.style.marginRight = '10px';
            const isChecked = index < 3 ? 'checked' : ''; // 默认前三列可见
            label.innerHTML = `
                <input type="checkbox" class="column-toggle" data-index="${index}" ${isChecked}> ${header}
            `;
            controlPanel.appendChild(label);
        });

        chatBlock.insertBefore(controlPanel, table);

        // 调用列切换处理函数
        handleColumnToggle(controlPanel, table);

        // 初始隐藏前三列以外的内容
        table.querySelectorAll('tr').forEach(row => {
            Array.from(row.children).forEach((cell, index) => {
                if (index >= 3) { // 隐藏前三列之外的列
                    cell.style.display = 'none';
                } else {
                    cell.style.display = ''; // 确保前三列显示
                }
            });
        });
    }

    // 处理列切换
    function handleColumnToggle(controlPanel, table) {
        controlPanel.querySelectorAll('.column-toggle').forEach(checkbox => {
            checkbox.addEventListener('change', function() {
                const columnIndex = parseInt(this.dataset.index, 10); // 确保将索引转换为数字
                const displayStyle = this.checked ? '' : 'none';
                table.querySelectorAll('tr').forEach(row => {
                    if (row.children[columnIndex]) { // 确保单元格存在
                        row.children[columnIndex].style.display = displayStyle;
                    }
                });
            });
        });
    }


    // 创建可编辑聊天块
    function createEditableChatBlock() {
        createChatBlock('', true);
    }

    // 显示加载旋转器
    function showLoadingSpinner() {
        togglePlusButton(false);
        const chatContent = document.getElementById('chatContent');
        if (chatContent) {
            chatContent.scrollTop = chatContent.scrollHeight;
        }
    }

    // 隐藏加载旋转器
    function hideLoadingSpinner() {
        togglePlusButton(true);
    }
</script>

{% endblock %}
